package com.example.frank.test2;

import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.frank.test2.HttpPost.HttpPost;
import com.example.frank.test2.Tools.BottomNavigationViewHelper;
import com.example.frank.test2.Tools.DragFloatActionButton;
import com.example.frank.test2.zxing.util.ZxingActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private ViewPager viewPager;
    private MenuItem menuItem;
    private BottomNavigationView navigation;
    private List<View> pagelist;
    private View view1, view2, view3, view4;
    private Button score_protect,game_protect;
    private String userid = "",cookie = "",stepCount_value = "",StepCount_error="";
    private TextView textView_title;
    private SensorManager sm;
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener;
    private WebView webView,webView2,webView3,webView4;
    private Integer stepCount;
    private ImageView imageView,btn,help;

    public static final int PAGE_ONE = 0;
    public static final int PAGE_TWO = 1;
    public static final int PAGE_THREE = 2;
    public static final int PAGE_FOUR = 3;

    public MainActivity() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = findViewById(R.id.imageView2);
        imageView.setVisibility(imageView.GONE);

        textView_title = findViewById(R.id.textView);
        textView_title.setText("数据录入");
        btn = findViewById(R.id.button1);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ZxingActivity.class);
                intent.putExtra("userid",userid);
                startActivity(intent);

            }
        });

        help = findViewById(R.id.help);
        help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int page = viewPager.getCurrentItem();
                Intent intent = new Intent(MainActivity.this,HelpActivity.class);
                intent.putExtra("page",page);
                startActivity(intent);

            }
        });

//        获取app使用时间
//        usage();

        //实例化底部导航
        navigation();

        //分页
        viewpage();

        //获取用户名
        getUserid();

//        webview设定
        webview1();
        webview2();
        webview3("http://39.106.192.16:3000/charts.html");
        webview3Button();
        webview4();

//        计步
        stepCount();


//        button2 = view1.findViewById(R.id.button2);
//        button2.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
//                startActivity(intent);
//            }
//        });

//        final Handler handler = new Handler();
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                // TODO Auto-generated method stub
//                try {
//                    dt = new Date();
//                    String date = dt.toLocaleString();
//                    date = datechanged(date);
//                    scv = stepcount_value - scv;
////                    Toast.makeText(MainActivity.this, " "+stepcount_value, Toast.LENGTH_SHORT).show();
//                    if (scv > 0) {
//                        value = value + ",{\"userID\":" + "\"" + userid + "\"" + ",\"types\":\"stepcount\",\"val\":" + "\"" + scv + "\"" + ",\"rec_time\":" + "\"" + date + "\"" + "}";
//                        scv = stepcount_value;
//                    }
//                    if (value.substring(value.length() - 1, value.length()) == "]") {
//                        value = "[" + value.substring(1, value.length());
//                    } else {
//                        str = "[" + value.substring(1, value.length()) + "]";
//                    }
//                    new Thread(new Runnable() {
//                        @Override
//                        public void run() {
//                            try {
//                                getReultForHttpPost(str, result);
//                                clear();
//                            } catch (IOException e) {
//                                String err = e.toString();
//                                Toast.makeText(MainActivity.this, err, Toast.LENGTH_SHORT).show();
//                            }
//                        }
//                    }).start();
//                } catch (Exception e) {
//                    e.getStackTrace();
//                }
//                handler.postDelayed(this, 15000);
//            }
//        };
//        handler.postDelayed(runnable, 15000);//每15秒执行一次runnable.


    }



    //    分页
    public void viewpage() {
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        LayoutInflater inflater = getLayoutInflater();
        view1 = inflater.inflate(R.layout.layout, null);
        view2 = inflater.inflate(R.layout.layout2, null);
        view3 = inflater.inflate(R.layout.layout3, null);
        view4 = inflater.inflate(R.layout.layout4, null);

        pagelist = new ArrayList<View>();// 将要分页显示的View装入数组中
        pagelist.add(view1);
        pagelist.add(view2);
        pagelist.add(view3);
        pagelist.add(view4);

        PagerAdapter pagerAdapter = new PagerAdapter() {

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                // TODO Auto-generated method stub
                return arg0 == arg1;
            }

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return pagelist.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position,
                                    Object object) {
                // TODO Auto-generated method stub
                container.removeView(pagelist.get(position));
            }

            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                // TODO Auto-generated method stub
                container.addView(pagelist.get(position));


                return pagelist.get(position);
            }
        };
        viewPager.setAdapter(pagerAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                if (menuItem != null) {
                    menuItem.setChecked(false);
                } else {
                    navigation.getMenu().getItem(0).setChecked(false);
                }

                menuItem = navigation.getMenu().getItem(position);
                menuItem.setChecked(true);

            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }

        });
    }

    //    获取用户名
    public void getUserid() {
        Intent intent = getIntent();
        userid = intent.getStringExtra("idcard");
//        textView = view1.findViewById(R.id.dcard_text);
//        textView.setText(userid);
        cookie = userid;
    }

    //    底部导航栏
    public void navigation() {

        navigation = (BottomNavigationView) findViewById(R.id.navigation);
        BottomNavigationViewHelper.disableShiftMode(navigation);
        mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.navigation_study:
                        textView_title.setText("数据录入");
                        viewPager.setCurrentItem(PAGE_ONE);
                        imageView.setVisibility(imageView.GONE);
                        btn.setVisibility(btn.VISIBLE);
                        return true;
                    case R.id.navigation_ai:
                        textView_title.setText("我的成绩");
                        viewPager.setCurrentItem(PAGE_TWO);
                        imageView.setVisibility(imageView.GONE);
                        btn.setVisibility(btn.GONE);
                        return true;
                    case R.id.navigation_teach:
                        textView_title.setText("AI预测");
                        viewPager.setCurrentItem(PAGE_THREE);
                        imageView.setVisibility(imageView.GONE);
                        btn.setVisibility(btn.GONE);
                        return true;
                    case R.id.navigation_score:
                        textView_title.setText("教学与评估");
                        viewPager.setCurrentItem(PAGE_FOUR);
                        imageView.setVisibility(imageView.VISIBLE);
                        btn.setVisibility(btn.GONE);
                        return true;
                }
                return false;
            }
        };

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

//    数据录入页面
    public void webview1(){
        webView = view1.findViewById(R.id.import_data);
        //创建CookieSyncManager
        CookieSyncManager.createInstance(this);
        //得到CookieManager
        CookieManager cookieManager = CookieManager.getInstance();
        //得到向URL中添加的Cookie的值
        String cookieString = "{\"uid\":"+"\""+cookie+"\"}";
        //使用cookieManager..setCookie()向URL中添加Cookie
        cookieManager.setCookie("file:///android_asset/pingce/index.html", cookieString);
        CookieSyncManager.getInstance().sync();
        webView.loadUrl("file:///android_asset/evaluation/index.html");
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

//    我的成绩页面
    public void webview2(){

        webView2 = view2.findViewById(R.id.score_look);
        webView2.loadUrl("http://39.106.192.16:3000/course.html");
        webView2.getSettings().setJavaScriptEnabled(true);
        webView2.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView2.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });

    }

//    AI预测页面
    public void webview3(String url){

        webView3 = view3.findViewById(R.id.layout3);
        webView3.loadUrl(url);
        webView3.getSettings().setJavaScriptEnabled(true);
        webView3.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView3.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });
    }

    public void webview3Button(){
        score_protect = view3.findViewById(R.id.score_protect);
        game_protect = view3.findViewById(R.id.game_protect);
        score_protect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview3("http://39.106.192.16:3000/charts.html");
            }
        });

        game_protect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview3("http://39.106.192.16:3000/ability.html");
            }
        });

    }

//    教学评估页面
    public void webview4(){
        webView4 = view4.findViewById(R.id.layout4);
        webView4.loadUrl("file:///android_asset/evaluation/list.html");
        webView4.getSettings().setJavaScriptEnabled(true);
        webView4.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView4.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view,String url) {
                view.loadUrl(url);
                return true;
            }
        });

        webView4.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && webView4.canGoBack()) {  //表示按返回键时的操作
                        webView4.goBack();   //后退
                        return true;    //已处理
                    }
                }
                return false;


            }
        });
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webView4.goBack();
            }
        });


    }

//    计步功能实现
    public void stepCount(){

        sm= (SensorManager) getSystemService(SENSOR_SERVICE);
        Sensor stepCounterSensor=sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);

        sm.registerListener(new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                String result;
                stepCount = (int) event.values[0];
                stepCount_value= "[{\"userid\"="+"\""+userid+"\",\"stepcount\"="+"\""+stepCount+"\"}]";
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            HttpPost.getReultForHttpPost(stepCount_value,StepCount_error);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {

            }
        },stepCounterSensor,SensorManager.SENSOR_DELAY_GAME);


    }



}
